package com.betterwood.dragon.worms;

import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import com.betterwood.dragon.entity.Result;
import com.betterwood.dragon.entity.Site;
import com.betterwood.dragon.entity.dto.SearchDTO;
import com.betterwood.dragon.utils.CodeUtil;
import com.betterwood.dragon.utils.TimeUtil;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.ElementHandle;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.options.ScreenshotType;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JF {
    // 济帆可用, 分页可用.
    public static String login(Site site) {
        log.info("#########################################");
        log.info("############START LOGIN TO JF############");
        String contextState = "EMPTY";

        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
            BrowserContext context = browser.newContext();

            // Open new page
            Page page = context.newPage();

            page.navigate("http://www.jfyy168.com");
            page.click("text=您好，请登录");
            page.click("#userId");
            // Fill input[name="userName"]
            // page.waitForTimeout(1500);
            page.fill("#userId", site.getUserName());
            // Press Enter

            page.click("#passWord");
            // Fill input[name="password"]
            page.fill("#passWord", site.getPassWord());
            page.waitForTimeout(3500);
            page.check("#xiacidenglu");
            ElementHandle elementHandle = page.querySelector("#vimg");
            byte[] screenBytes = elementHandle.screenshot(new ElementHandle.ScreenshotOptions()
                    .setPath(Paths.get("screenshot.png")).setType(ScreenshotType.PNG));
            String vCode = CodeUtil.decode(screenBytes);
            log.info("*************");
            log.info(vCode);
            log.info("*************");

            page.fill("#vcode", vCode);

            // Press Enter
            // page.waitForNavigation(new
            // Page.WaitForNavigationOptions().setUrl("http://bh.ry600.com/_shop/index.shtml"),
            // () ->
            page.waitForNavigation(() -> {
                page.click("#login_id");
            });
            // ---------------------

            contextState = context.storageState();
            // log.info(contextState);
            log.info("############END OF LOGIN TO JF#############");

        } catch (RuntimeException e) {
            e.printStackTrace();

        }
        return contextState;
    }

    public static List<Result> fetchProduct(Site site, SearchDTO search) {
        log.info("#######################################");
        log.info("############START FETCH FROM JF########");
        List<Result> initList = new ArrayList<>();

        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
            String storageState = site.getLoginInfo();
            BrowserContext context = browser.newContext(new Browser.NewContextOptions().setStorageState(storageState));

            // Open new page
            Page page = context.newPage();
            page.navigate(site.getSiteUrl());
            log.info("**********");
            log.info(search.getKeywordStr());
            log.info("**********");
            page.click("#guolvtj");

            page.fill("#guolvtj", search.getKeywordStr());

            page.waitForNavigation(() -> {
                page.click("text=搜索");
            });

            // String wait = page.textContent(".spxsjSpanCss");

            // page.selectOption("select", "90");
            // page.waitForTimeout(1500);
            // page.pause();

            String pager = page.innerHTML("#page");
            // log.info(pager);
            Document pagerDoc = Jsoup.parseBodyFragment(pager);
            Element rightArrow = pagerDoc.getElementsByClass("layui-laypage-next").first();
            // log.info(rightArrow.classNames().toString());
            boolean hasNext = !rightArrow.classNames().contains("layui-disabled");

            String content = page.innerHTML("#itemSearchList");
            initList = getList(content, search, site);
            List<Result> otherList = new ArrayList<>();
            while (hasNext) {
                page.click(".layui-laypage-next");
                page.waitForTimeout(2500);
                content = page.innerHTML("#itemSearchList");

                pager = page.innerHTML("#page");
                pagerDoc = Jsoup.parseBodyFragment(pager);
                otherList = getList(content, search, site);
                initList.addAll(otherList);

                rightArrow = pagerDoc.getElementsByClass("layui-laypage-next").first();
                hasNext = !rightArrow.classNames().contains("layui-disabled");
            }
            // log.info(content);

        } catch (RuntimeException e) {
            log.info(e.toString());
            log.info("WORM JF FAILED");
        }

        log.info("END OF fetch product");
        log.info("**************FOUND NEW PRODUCTS!!!******************");
        log.info(Integer.toString(initList.size()));
        log.info("**************FOUND NEW PRODUCTS!!!******************");
        return initList;
    }

    public static List<Result> getList(String content, SearchDTO search, Site site) {

        List<Result> list = new ArrayList<>();

        Document doc = Jsoup.parseBodyFragment(content);
        Element body = doc.body();

        Elements lis = body.getElementsByClass("mod_search_pro");

        if (lis.size() == 0) {
            log.info("JF HAVE NO RESULTS");
            return list;
        }

        for (Element li : lis) {

            Element nameElement = li.getElementsByClass("proName").first();
            Element aElement = nameElement.getElementsByTag("a").first();
            String pName = aElement.attributes().get("title");

            Element proElement = li.getElementsByClass("o_1").first();
            Element makerElement = li.getElementsByClass("o_1").get(1);
            String prop = proElement.attributes().get("title");
            String maker = makerElement.attributes().get("title");

            Element priceEle = li.getElementsByClass("proPrice").first();
            Element emElement = priceEle.getElementsByTag("em").get(1);
            String price = emElement.text();
            String priceClean = StrUtil.split(price, "¥")[1];

            Double priceDouble = NumberUtil.isNumber(priceClean) ? Double.parseDouble(priceClean) : 0;

            String productName = StrUtil.concat(true, pName, prop, maker);

            Result re = new Result();

            // log.info("规格是:" + prop);
            // log.info("厂家是" + maker);
            re.setKeywordStr(search.getKeywordStr());
            re.setProp(prop);
            re.setMaker(maker);
            re.setProductName(productName);
            re.setOrderUrl(site.getSiteUrl());
            re.setScanTime(TimeUtil.currentTime());

            re.setSearchId(search.getId());
            re.setSiteName("济帆");
            // // // // re.setSiteId("");
            re.setSiteNo("JF");
            re.setScanPrice(priceClean);

            re.setPrice(priceDouble);
            re.setStatus(0);

            // // // // resultDao.save(re);
            list.add(re);

        }

        // return "SUCCESS";
        // log.info("WORM JF SUCCESS");

        // Result r = new Result();
        // r.setKeywordStr("KEY_WD");
        // r.setOrderUrl("ORDER_URL");
        // list.add(r);
        return list;
    }
}
